package com.qg.cyapp.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.qg.cyapp.R;
import com.qg.cyapp.bean.FoodBean;
import com.qg.cyapp.component.SearchWaterFall;
import com.qg.cyapp.component.WaterFall;
import com.qg.cyapp.util.ShareUtil;

/**
 * @author xuan 2014-10-30
 * 
 */
public class SearchShowActivity extends HttpActivity implements
		SearchWaterFall.ScrollToBottomListener {

	private TextView tvReturn, tvSearch;
	private LinearLayout llShow;
	private WaterFall wfFoods;
	public static List<FoodBean> foods = new ArrayList<FoodBean>();
	private String searchWord;
	private int startId = 0;
	private int number = 6;

	@Override
	public int getLayoutId() {
		return R.layout.activity_search;
	}

	@Override
	public void setUI() {
		searchWord = this.getIntent().getStringExtra(ShareUtil.SEARCH_KEY);
		Log.v("SearchWord", searchWord);
		tvReturn = (TextView) mfindViewAndSetOnClick(R.id.tv_back);
		tvSearch = (TextView) findViewById(R.id.tvSearch);
		tvSearch.setText(searchWord);
		llShow = (LinearLayout) findViewById(R.id.llSearchFood);

		wfFoods = new SearchWaterFall(this, foods);
		wfFoods.init(3);
		llShow.addView(wfFoods);

		getSearchFood(searchWord);
	}

	public void getSearchFood(String searchWord) {
		params.clear();
		params.put("param", searchWord);
		params.put("action", "searchFood");
		params.put("menudirno", ShareUtil.NORMAL_FOOD);
		params.put("startId", String.valueOf(startId));
		params.put("number", String.valueOf(number));
		addPostRequest("GetFoodAction", params, 0);
		sendPostRequest();
	}

	@Override
	public void OnClickListener(View view) {
		switch (view.getId()) {
		case R.id.tv_back:
			this.finish();
		}
	}

	@Override
	public void afterPost(String result, int requestCode,
			Map<String, String> request) {
		// TODO Auto-generated method stub
		bean = getGsonBean(result);
		if (bean.state == ShareUtil.SUCCESS) {
			List<FoodBean> newFoods = gson.fromJson(bean.json,
					new TypeToken<List<FoodBean>>() {
					}.getType());
			if (newFoods.size() > 0) {
				startId += newFoods.size();
				foods.addAll(newFoods);
				wfFoods.notifyDataSetChanged();
			}

		}
	}

	public String getEditTextString(EditText et) {
		Editable ea = et.getText();
		if (ea == null) {
			return null;
		} else {
			return ea.toString();
		}
	}

	@Override
	public void scrollToBottom() {
		// TODO Auto-generated method stub
		getSearchFood(searchWord);
	}

}
